package org.koyad.portal.context;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.exceptions.FrameworkException;
import org.koyad.portal.tags.ViewRoot;
import org.koyad.portal.utils.LogUtils;

public final class PistonContext {

	private static final LogUtils LOGGER = LogUtils.getLogger(PistonContext.class);

	private HttpServletRequest _request = null;
	private HttpServletResponse _response = null;
	private ViewRoot _viewRoot = null;
	
	// constructor
	private PistonContext() {
	}

	// getters and setters
	public final HttpServletRequest getRequest() {
		return _request;
	}

	public final HttpServletResponse getResponse() {
		return _response;
	}

	public final ServletContext getApplication() {
		return _request.getServletContext();
	}

	public ViewRoot getViewRoot() {
		if (null == _viewRoot) {
			PistonSession session = (PistonSession)_request.getSession(false);
			if (null != session) {
				_viewRoot = session.getViewRoot();
			}
		}
		return _viewRoot;
	}

	public void setViewRoot(ViewRoot viewRoot) {
		HttpSession session = _request.getSession(viewRoot.isSession());
		if (null != session) {
			session.setAttribute(FrameworkConstants.PISTON_VIEW_ROOT, viewRoot);
		}
		_viewRoot = viewRoot;
	}

	public void resetViewRoot() {
		if (null != _request.getSession(_viewRoot.isSession())) {
			_request.getSession().removeAttribute(FrameworkConstants.PISTON_VIEW_ROOT);
		}
		_viewRoot = null;
	}

	private static final ThreadLocal<PistonContext> context = new ThreadLocal<PistonContext>() {
		@Override
		protected PistonContext initialValue() {
			return new PistonContext();
		};
	};

	/**
	 * This will be called by portal servlet.
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws FrameworkException
	 */
	public static final PistonContext initialize(HttpServletRequest request, HttpServletResponse response) throws FrameworkException {
		PistonContext pistonCtx = context.get();

		if (null == pistonCtx._request) {
			pistonCtx._request = request;
		}

		if (null == pistonCtx._response) {
			pistonCtx._response = response;
		}

		return pistonCtx;
	}

	public static final PistonContext getContext() throws FrameworkException {
		return context.get();
	}

}
